package com.blame.onlinemusicserver.config;

import com.blame.onlinemusicserver.tools.Constant;
import com.blame.onlinemusicserver.tools.ResponseBodyMessage;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;



@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
        System.out.println("当前请求路径：" + uri);

        // 放行登录和注册路径
        if (uri.startsWith("/user/login") || uri.startsWith("/user/register")) {
            return true;
        }

        // 检查会话中的用户信息
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(Constant.USERINFO_SESSION_KEY) != null) {
            return true;
        }

        // 未登录提示
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write("{\"code\":401,\"msg\":\"未登录，请先登录\"}");
        return false;
    }
}

